/*
 * 项目名称:platform-plus
 * 类名称:CustomerController.java
 * 包名称:com.platform.modules.customer.controller
 *
 * 修改履历:
 *     日期                       修正者        主要内容
 *     2020-10-10 14:34:32        klwu     初版做成
 *
 * Copyright (c) 2019-2019 klwu
 */
package com.platform.modules.custmoer.controler;

import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.google.gson.JsonArray;
import com.google.gson.JsonElement;
import com.google.gson.JsonObject;
import com.platform.common.annotation.SysLog;
import com.platform.common.exception.BusinessException;
import com.platform.common.utils.*;
import com.platform.modules.custmoer.dto.CustomerDetailDto;
import com.platform.modules.custmoer.dto.MyCustomersDto;
import com.platform.modules.custmoer.entity.CustRecordEntity;
import com.platform.modules.custmoer.entity.CustomerEntity;
import com.platform.modules.custmoer.entity.StaffEntity;
import com.platform.modules.custmoer.service.CustRecordService;
import com.platform.modules.custmoer.service.CustomerService;
import com.platform.modules.custmoer.service.StaffMapService;
import com.platform.modules.custmoer.service.StaffService;
import com.platform.modules.httpclient.HttpClient;
import com.platform.modules.httpclient.HttpMethod;
import com.platform.modules.httpclient.HttpParamers;
import com.platform.modules.sys.controller.AbstractController;
import com.platform.modules.utils.LocationUtil;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletRequest;
import java.io.File;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

/**
 * Controller
 *
 * @author klwu
 * @date 2020-10-10 14:34:32
 */
@RestController
@RequestMapping("customer/")
public class CustomerController extends AbstractController {
    @Autowired
    private CustomerService customerService;
    @Autowired
    private StaffService staffService;
    @Autowired
    private CustRecordService custRecordService;
    @Autowired
    private StaffMapService staffMapService;

    /**
     * 查看所有列表
     *
     * @param params 查询参数
     * @return RestResponse
     */
    @RequestMapping("/queryAll")
    @RequiresPermissions("customer::list")
    public RestResponse queryAll(@RequestParam Map<String, Object> params) {
        List<CustomerEntity> list = customerService.queryAll(params);

        return RestResponse.success().put("list", list);
    }

    /**
     * 全国客户和今日新增
     * @param params
     * @return
     */
    @RequestMapping("/queryAllCount")
    public RestResponse All(@RequestParam Map<String, Object> params) {
        List<CustomerEntity> list = customerService.queryAll(params);
        List<CustomerEntity> todayCoust = list.stream().filter(s -> DateUtils.format(s.getCreateTime(),DateUtils.DATE_PATTERN).equals(DateUtils.format(new Date(),DateUtils.DATE_PATTERN))).collect(Collectors.toList());
        return RestResponse.success().put("total", list.size()).put("today",todayCoust.size());
    }



    /**
     * 分页查询
     *
     * @param params 查询参数
     * @return RestResponse
     */
    @GetMapping("/list")
    @RequiresPermissions("customer::list")
    public RestResponse list(@RequestParam Map<String, Object> params) {
        Page page = customerService.queryPage(params);

        return RestResponse.success().put("page", page);
    }

    /**
     * 根据主键查询详情
     *
     * @param id 主键
     * @return RestResponse
     */
    @RequestMapping("/info/{id}")
    @RequiresPermissions("customer::info")
    public RestResponse info(@PathVariable("id") String id) {
        CustomerEntity customer = customerService.getById(id);
        customer.setCreateTimeStr(DateUtils.format(customer.getCreateTime(),DateUtils.DATE_PATTERN));
        if("0".equals(customer.getStatus())){
            customer.setStatusStr("低意向");
        }else if ("1".equals(customer.getStatus())){
            customer.setStatusStr("中意向");
        }else if("2".equals(customer.getStatus())){
            customer.setStatusStr("高意向");
        }
        if(!StringUtils.isEmpty(customer.getStaffId())){
            customer.setStaffName(staffService.getById(customer.getStaffId()).getName());
        }
        CustomerDetailDto customerDetailDto = customerService.constructionDetail(customer);

        return RestResponse.success().put("data", customer).put("record",customerDetailDto);
    }

    /**
     * 新增
     *
     * @param customer customer
     * @return RestResponse
     */
    @SysLog("新增")
    @RequestMapping("/save")
    @RequiresPermissions("customer::save")
    public RestResponse save(@RequestBody CustomerEntity customer) {
        customer.setCreateTime(new Date());
        String address = customer.getProvince() + customer.getCity() + customer.getTown() + customer.getAddress();
        String lgt = "";
        String lat = "";
        if(StringUtils.isNotBlank(address)){
            try {
                LocationUtil locationUtil = new LocationUtil();
                Object[] coordinate = locationUtil.getCoordinate(address);
                lgt = (String) coordinate[0];
                lat = (String) coordinate[1];
            }catch (Exception e){
                e.printStackTrace();
            }
        }
        customer.setLat(lat);
        customer.setLgt(lgt);
        customerService.add(customer);
        CustRecordEntity record = new CustRecordEntity();
        record.setCustId(customer.getId());
        record.setRecord(customer.getRemark());
        record.setCreateTime(new Date());
        custRecordService.save(record);
        return RestResponse.success();
    }

    /**
     * 修改
     *
     * @param customer customer
     * @return RestResponse
     */
    @SysLog("修改")
    @RequestMapping("/update")
    @RequiresPermissions("customer::update")
    public RestResponse update(@RequestBody CustomerEntity customer) {

        customerService.update(customer);

        return RestResponse.success();
    }

    /**
     * 根据主键删除
     *
     * @param ids ids
     * @return RestResponse
     */
    @SysLog("删除")
    @RequestMapping("/delete")
    public RestResponse delete(@RequestBody String[] ids) {
        customerService.deleteBatch(ids);

        return RestResponse.success();
    }

    /**
     * 查询首页列表数据
     * @param params
     * @return
     */
    @GetMapping("/homeList")
    @RequiresPermissions("customer::list")
    public RestResponse homeList(@RequestParam Map<String, Object> params) {
        Page page = customerService.queryHomeListPage(params);
        return RestResponse.success().put("page", page);
    }

    @GetMapping("/staffmap")
    public RestResponse staffMap(@RequestParam Map<String, Object> params) {
        Page page = staffMapService.queryPage(params);
        return RestResponse.success().put("page", page);
    }

    /**
     * 客户列表趋势图
     * @param params
     * @return
     */
    @GetMapping("/getDays")
    //@RequiresPermissions("customer::list")
    public RestResponse getDays(@RequestParam Map<String, Object> params) {
        List<String> days = customerService.getLastDays(params);
        List<Integer> nums = new ArrayList();
        params.put("diff",7);
        List<MyCustomersDto> Customers = customerService.selectlastThreeDay(params);
        int one = 0;
        int two = 0;
        int thrid = 0;
        int four = 0;
        int five = 0;
        int six = 0;
        int sev = 0;
        for(MyCustomersDto my : Customers){
            Date createTime = my.getCreateTime();
            String format = DateUtils.format(createTime, DateUtils.DATE_PATTERN);
            if(format.equals(days.get(0))){
                one ++;
            }
            if(format.equals(days.get(1))){
                two ++;
            }
            if(format.equals(days.get(2))){
                thrid ++;
            }
            if(format.equals(days.get(3))){
                four ++;
            }
            if(format.equals(days.get(4))){
                five ++;
            }
            if(format.equals(days.get(5))){
                six ++;
            }
            if(format.equals(days.get(6))){
                sev ++;
            }
        }
        nums.add(one);
        nums.add(two);
        nums.add(thrid);
        nums.add(four);
        nums.add(five);
        nums.add(six);
        nums.add(sev);
        return RestResponse.success().put("days", days).put("Customers",Customers).put("nums",nums);
    }

    /**
     * 订单趋势图
     * @param
     * @return
     */
    @GetMapping("/home/orders")
    public RestResponse getSivDaysOrders() throws IOException {
        String url = "http://verify.mengtelaidi.com/api/sevenDayCounts?token=eyJhbGciOiJIUzI1N";
        HttpParamers httpParamers = new HttpParamers(HttpMethod.GET);
        String result = HttpClient.doGet(url, httpParamers, null, 6000, 6000);
        System.out.println(result);
        JsonObject jsonObj = JsonUtils.getJsonObj(result);
        if(jsonObj.get("code").getAsInt() != 200){
            throw new BusinessException("调用外部接口返回编码="+jsonObj.get("code").getAsInt());
        }
        JsonArray data = jsonObj.get("data").getAsJsonArray();
        List<Integer> counts = new ArrayList<>();
        List<String> days = new ArrayList<>();
        for(int i=1;i<data.size();i++){
            JsonElement jsonElement = data.get(i);
            int count = jsonElement.getAsJsonObject().get("counts").getAsInt();
            String countDate = jsonElement.getAsJsonObject().get("countDate").getAsString();
            counts.add(count);
            days.add(countDate);
        }
        return RestResponse.success().put("counts", counts).put("days",days);
    }

    //用于接收文件
    @RequestMapping("/uploadExcel")
    @ResponseBody
    public RestResponse upload(MultipartFile file, HttpServletRequest request) throws IOException {
        Map<String, List<String[]>> stringListMap = EasyPoiUtils.readExcel(file);
        customerService.handleExcel(stringListMap);
        return RestResponse.success();
    }

    @RequestMapping("/home/calculate")
    public RestResponse homeDataCalculate(){
        double custTotal = customerService.custTotal();
        double precustTotal = customerService.precustTotal();
        double staffTotal = staffService.staffTotal();
        double prestaffTotal = staffService.prestaffTotal();
        double recordTotal = custRecordService.recordTotal();
        double prerecordTotal = custRecordService.prerecordTotal();
        double custadd = 0.0;
        if(precustTotal !=0){
            custadd = (custTotal - precustTotal) / precustTotal * 100;
        }
        double staffadd = 0.0;
        if(prestaffTotal !=0){
            staffadd = (staffTotal - prestaffTotal) / prestaffTotal * 100;
        }
        double recordadd = 0.0;
        if(prerecordTotal !=0){
            recordadd = (recordTotal - prerecordTotal) / prerecordTotal * 100;
        }

        // 订单总数
        String url = "http://verify.mengtelaidi.com/api/ordersCount?token=eyJhbGciOiJIUzI1N";
        String url2 = "http://verify.mengtelaidi.com/api/dayAdd?token=eyJhbGciOiJIUzI1N";// 增长率
        HttpParamers httpParamers = new HttpParamers(HttpMethod.GET);
        int totalOrder = 0;
        double OrderAdd = 0.0;
        try {
            String result = HttpClient.doGet(url, httpParamers, null, 6000, 6000);
            String result2 = HttpClient.doGet(url2, httpParamers, null, 6000, 6000);
            JsonObject jsonObj = JsonUtils.getJsonObj(result);
            JsonObject jsonObj2 = JsonUtils.getJsonObj(result2);
            if(jsonObj.get("code").getAsInt() != 200){
                throw new BusinessException("调用外部接口返回编码="+jsonObj.get("code").getAsInt());
            }
            if(jsonObj2.get("code").getAsInt() != 200){
                throw new BusinessException("调用外部接口返回编码="+jsonObj.get("code").getAsInt());
            }
            totalOrder = jsonObj.get("data").getAsInt();
            OrderAdd = jsonObj2.get("data").getAsFloat();

        }catch (Exception e){

        }

        return RestResponse.success().put("custPersionsTotal",(int)custTotal)
                .put("custAdd",String.valueOf(custadd)+"%")
                .put("staffPersionTotal",(int)staffTotal)
                .put("staffadd",String.valueOf(staffadd)+"%")
                .put("recordTotal",(int)recordTotal)
                .put("recordadd",String.valueOf(recordadd)+"%")
                .put("totalOrder",totalOrder)
                .put("OrderAdd",OrderAdd);
    }

    @RequestMapping("/home/totalOrder")
    public RestResponse getTotalOrder(){

        return RestResponse.success();
    }



}
